<template>
  <div class="layout-container">
    <div class="layout-container-form" style="flex-direction: column">
      <div class="layout-container-form-search">
        <el-row style="text-align: left">
          <el-col :span="24">
            <el-form label-width="90px" :inline="true">
              
              <el-form-item label="栏目：" label-width="110px" >
                <el-select v-model="query.column_id" placeholder="请选择状态" filterable  style="width: 100%" clearable
                    @change="getTableData(true)">
                    <el-option v-for="item in columnOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="题目名称：">
                <el-input v-model="query.title" placeholder="请输入题目名称" style="width: 100%"
                  @keyup.enter="getTableData(true)"></el-input>
              </el-form-item>
              <el-form-item>
                 <el-button
                  v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions && adminInfo.action_permissions.includes('3'))"
                  :type="query.column_id ? 'primary' : ''" :disabled="!query.column_id" 
                  :loading="exportBatchLoading" @click="handleOpt({},1,1)">
                  删除栏目
                </el-button>
                <el-button class="search-btn" style="margin-left: 8px" @click="resetSearch">{{
                    $t("message.common.reset")
                }}</el-button>
                <el-button type="primary" class="search-btn" @click="getTableData(true)">{{ $t("message.common.search")
                }}</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
      <div class="layout-container-opt" style="">
         <div style="padding:0 20px 0 18px">
            <el-checkbox v-model="checkAll" label="1" @change="changeAll">全选</el-checkbox>
        </div>
        <el-button
          v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions && adminInfo.action_permissions.includes('3'))"
          :type="'primary'"
          @click="handleAdd">
          新增文章
        </el-button>
        <el-button
          v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions && adminInfo.action_permissions.includes('3'))"
          :type=" 'primary'" :disabled="selectData.length === 0"
          :loading="exportBatchLoading" @click="exportExcelFun">
          导出勾选文章
        </el-button>
        
        <el-button
          v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions && adminInfo.action_permissions.includes('3'))"
          :type="selectData.length > 0 ? 'primary' : ''" :disabled="selectData.length === 0"
          :loading="exportBatchLoading" @click="handleOpt({},1,6)">
          批量删除勾选文章
        </el-button>
        <el-button class="search-btn" icon="el-icon-refresh-right" style="position:absolute;right:0;bottom:8px;"
          @click="getTableData(true)">{{ $t("message.common.refresh") }}</el-button>
      </div>
    </div>
    <div class="layout-container-table">
      <Table ref="table" v-model:page="page" v-loading="loading" :showSelection="true"
       :data="tableData"
        @getTableData="getTableData" @selection-change="handleSelectionChange">
            <el-table-column 
            v-for="(item,index) in columns" :type="item.type" :key="index"
            :label="item.label"
            :width="item.width"
            :property="item.property">
                <template #default="scope" v-if="item.input">
                    <el-input  @blur="handleOpt(scope.row,scope.$index,7)" v-model="scope.row.sort" placeholder="" />
                </template>
                <template #default="scope" v-else-if="item.switch">
                    <el-switch 
                     @change="((e) =>{changeStatus(e,scope.row,scope.$index)})" v-model="scope.row.status"></el-switch>
                </template>
                <template #default="scope" v-else-if="item.copy">
                    <span>{{scope.row[item.property]}} '
                        <el-icon class="cup" v-copy="scope.row[item.property]"  color="#409eff"><DocumentCopy /></el-icon>
                    </span>
                </template>
                <template #default="scope" v-else-if="item.image">
                    <el-image
                      v-if="scope.row[item.property]"
                      style="width: 80px; height: 50px; cursor: pointer;"
                      :src="scope.row[item.property]"
                      :preview-src-list="[scope.row[item.property]]"
                    />
                    <div
                      v-else
                      class="no-img"
                    >
                      暂无图片
                    </div>
                </template>
                <template #default="scope" v-else-if="item.tooltip">
                    <el-popover
                        placement="bottom"
                        @show="(()=>{getHistoryPeopleLevel(scope.row)})"
                        :disabled="scope.row[item.property] ==''?true:false"
                        trigger="hover">
                        <div slot="content">
                            <template v-if="item.property == 'team_people_level'">
                                <div v-for="(el, i) in historyPeopleLevelArr" :key="i">
                                    {{el}}
                                </div>
                            </template>
                            <template v-else>
                                {{scope.row[item.property]}}
                            </template>
                            
                        </div>
                        <template #reference>
                            
                             <template v-if="item.property == 'remark' || item.property == 'delivery_address'">
                                <span v-if="scope.row[item.property] == ''">无</span>
                                <el-button v-else type="text">查看</el-button>
                            </template>
                            
                            <el-button v-else type="text">{{scope.row[item.property]}}</el-button>
                        </template>
                    </el-popover>
                </template>
                <template  #default="scope" v-else>
                    <template v-if="item.property">
                        <el-input
                           
                            v-if="scope.row.showInput" 
                            v-model="scope.row[item.property]" 
                            placeholder="" />
                        <span v-else :class="[item.classes]">{{scope.row[item.property]}}</span>
                    </template>
                </template>
                
            </el-table-column>
            <el-table-column label="操作" width="220">
                <template #default="scope">
                    <el-button type="" @click="goApp(scope.row,scope.$index)">预览</el-button>
                    <el-button type="danger" @click="handleOpt(scope.row,scope.$index,4)">删除</el-button>
                    <el-button type="success" @click="handleAdd(scope.row,scope)">修改</el-button>
                    
                </template>
            </el-table-column>
      </Table>
    </div>
      <!-- 上传文件弹出框组件 -->
        <BatchImportDialog 
        v-if="uploadObj.visible"
        :visible="uploadObj.visible"
        :title="uploadObj.title"
        :uploadObj="uploadObj"
        @closeUploadDialog="closeUploadDialog"
        @refreshTable="refreshTable"/>
  </div>
</template>
<script setup lang="ts">
import {  ref, reactive ,onActivated, nextTick} from "vue";
import { Page } from "@/components/table/type";
import { ElMessage, ElMessageBox ,ElIcon } from "element-plus";
import BatchImportDialog from "@/components/uploadFile/batchImportDialog.vue";
import Table from "@/components/table/index.vue";
import {
  productList,productUpdate,productPicture,productImports
} from "@/api/exchange.ts";
import {
  notifyList,notifyColumnList,deleteNotify,modifyNotify,delNotifyColumn
} from "@/api/notice.ts";


import { dateFormat, intervalTime, calculateDiffTime } from "@/utils/index.ts";
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";
import { ossPrefixNew } from "@/utils/index.ts";
const router = useRouter();
const store = useStore();
const adminInfo = reactive(store.state.user.adminInfo);

// 存储搜索用的数据
const query = reactive({
  "column_id":"",
  "title":"",
});
const columnOptions = ref([])
const getNotifyColumnList = ()=>{
  notifyColumnList().then(res => {
    if(res.code == 200){
      res.data.map(item => {
        item.label = item.name
        item.value = item.Id
      })
      columnOptions.value = res.data;
    }
    
  })
}



// 分页参数, 供table使用
const page: Page = reactive({
  index: 1,
  size: 50,
  total: 0,
});
// 重置
const resetSearch = () => {
    query.column_id = ''//
    query.title = ''//, // string
    getTableData(true);
}
const columns = ref([])
const columns1 = reactive([
    {
        label:'ID',
        property:'Id', 
        width:'55',
    },
    {
        label:'栏目',
        property:'column_name',
    },{
        label:'标题',
        property:'title',
        width:'400px',
    },{
        label:'发布时间',
        property:'created_at',
    },{
        label:'排序',
        property:'sort',
        input:true,
    },{
        label:'状态',
        property:'statusName',
        switch:true,
    },{
        label:'访问量',
        property:'views',
    },
]);
columns.value = columns1
const loading = ref(false);
const tableData = ref([]);

const getParams = ()=>{
    let obj = {
        page: page.index,
        page_size: page.size,
        "column_id":"",
        "title":"",
        ...query
    }
    obj.column_id =  obj.column_id == undefined ? -1 : obj.column_id +''
    Object.keys(obj).map(item => {
        if(obj[item] == ''){
            delete obj[item]
        }
    })
    if(obj.status == -1){
        delete obj.status
    }
    return obj
}

const table = ref()
const checkAll = ref(false)
const changeAll = (e:any)=>{
    console.log(checkAll.value)
    if(e){
      if(selectData.value.length == tableData.value.length) return
        table.value.$refs.systemTable.toggleAllSelection()
    }else{
      selectData.value = [];
      table.value.$refs.systemTable.clearSelection()
    }
}
// 勾选数据
const selectData = ref([]); // 系统id
const handleSelectionChange = (data: any) => {
  selectData.value = [];
  if(data.length){
    if(data.length != tableData.value.length){
      checkAll.value = false
    }
    data.forEach((item: any) => {
      selectData.value.push(item.Id);
    });
  }
};

// 获取表格数据
// params <init> Boolean ，默认为false，用于判断是否需要初始化分页
const getTableData = (init: Boolean) => {
  loading.value = true;
  if (init) {
    page.index = 1;
  }
  let params = getParams()
  notifyList(params)
    .then((res: any) => {
      let data = res.data.list;
      data.forEach((d: any) => {
        d.loading = false;
        d.status = d.status == 1?true:false
        d.created_at = dateFormat(d.created_at)
       
      });
      tableData.value = data;
      if(checkAll.value){
          changeAll(true)
      }else{
        changeAll(false)
      }
      page.total = Number(res.data.count);
    })
    .catch(() => {
      d.loading = false;
      tableData.value = [];
      page.index = 1;
      page.total = 0;
    })
    .finally(() => {
      loading.value = false;
    });
};
onActivated(()=>{
  getNotifyColumnList()
})
// 状态change事件
const changeStatus = (e:boolean,row:any,index:any) => {
  if(!loading.value){
      console.log(e)
      let par = {
        id:row.Id,
        status:(e?1:0) + '',
      }
      setModifyNotify(par)
  }
  setTimeout(() => {
    loading.value = false;
  }, 100);
}
const setModifyNotify = (par:object)=>{
  modifyNotify(par).then(res =>{
    if(res.code == 200){
      getTableData()
    }
  })
}
const tooltipType = ref('')
const historyPeopleLevelArr = ref([]);
const getHistoryPeopleLevel = (row:any)=>{
    if(row.property == ''){
        historyPeopleLevel({id:row.Id}).then(res => {
            if(res.code == 200){
                historyPeopleLevelArr.value =res.data.list 
            }else{
                ElMessage.success(res.message);
            }
        })
    }
    
}
//新建项目通知
const handleAdd = (item:any) => {
  router.push({
    path: '/backstagerpzzm/notificationMessage/addArticle',
    query:{
      id:item!.Id
    }
  })
}//新建项目通知
const goApp = (item:any) => {
  debugger
  let host = window.location.host;
  let hostname = window.location.hostname;
  let url = ''
  if(host.indexOf('localhost') > -1 || host.indexOf('192.168') > -1){
    url = 'http://192.168.13.119:8080/work/pages/article/article?id='+item.Id
  }else {
     if(host.indexOf('47.') > -1){
      url = 'http://47.93.156.6:8087/work/pages/article/article?id='+item.Id
    }else if(host.indexOf('new.zhaixiaozhi.com')> -1){
       url = 'http://' + hostname + ':8888/work/pages/article/article?id=' + item.Id
    }else{
      url = 'https://' + hostname + '/work/pages/article/article?id=' + item.Id
    } 
  }
  
  // if(host.indexOf('47.') > -1){
  //   url = 'http://47.93.156.6:8087/work/pages/article/article?id='+item.Id
  // }else{
  //   url = 'https://www.zhaixiaozhi.com/work/pages/article/article?id=' + item.Id
  // }
  window.open(url)
}
// 操作
const handleOpt = (row: any ,index:Number,type: Number) => {
   let par = {
      id:row.Id,
    }
  if(type == 7){
    par.sort = row.sort+''
    setModifyNotify(par)
    return
  }
  ElMessageBox.confirm(`是否确认当前操作?`, "", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "success",
  })
    .then(() => {

      if(type == 6){//批量删除
        par = {
          ids: selectData.value,
        }
        if(checkAll.value){
          par.ids = []
        }
         delete par.id
      }else if(type == 1){//删除栏目
        par = {
          id: query.column_id,
        }
        delNotifyColumnFunc(par)
        return 
      }else if(type == 4){
        par = {
          ids:[row.Id],
        }
        delete par.id
      }
      
      setProfileUdate(par,row,index)
    })
    .catch(() => { });
};

const setProfileUdate = (par:any,)=> {
    deleteNotify(par).then(res => {
        if(res.code == 200){
           ElMessage.success('操作成功！');
           if(checkAll.value){
            checkAll.value = false
           }
           getTableData()
        }else{
           ElMessage.success(res.message);
        }
    })
}
const delNotifyColumnFunc = (par:any,)=> {
    delNotifyColumn(par).then(res => {
        if(res.code == 200){
          ElMessage.success('操作成功！');
          getNotifyColumnList()
          query.column_id = ''
          getTableData(true)
        }else{
           ElMessage.success(res.message);
        }
    })
}

const uploadObjImg = reactive({
  accept: ".png, .jpg, .jpeg",
});

const uploadFileFun = (fileInfo: any,row:any,index:any) => {
  let file = fileInfo.file;
  const fileType = [".png", ".jpg", ".jpeg"];
  const type = file.name.substr(file.name.lastIndexOf(".")).toLowerCase();
  // 上传类型限制
  if (!fileType.includes(type)) {
    let type = fileType.join("，");
    ElMessage.error(`温馨提示：只支持${type}格式的文件`);
    return;
  }
  // 上传大小限制
  const sizeLimit = file.size / 1024 / 1024 <= 5;
  if (!sizeLimit) {
    ElMessage.error("文件最大不能超过5MB");
    return;
  }

  let formData = new FormData();
  formData.append("file", file);
  formData.append("product_id", row.product_id);

  let data = {
    data: formData,
  };
  productPicture(data).then((res: any) => {
    if (res.code) {
      ElMessage.success(`上传成功`);
      tableData.value.splice(index,1,{...row,product_picture_path:res.data})
    }
  });
};


// 导出题目答案与表格
const exportBatchLoading = ref(false);
const exportSingleLoading = ref(false);
const exportExcelFun = () => {
  exportBatchLoading.value = true;
  exportExcelPost(selectData.value, selectProjectIdsData.value)
}
// 导出通用函数
const exportExcelPost = (topic_ids: any, project_ids: any) => {
  let data = {
    topic_ids: topic_ids, // array[interger]
    // project_ids: project_ids, // array[string]
  }
  exportExcel(data).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success('导出成功');
      window.open(res.data);
    }
  }).finally(() => {
    exportBatchLoading.value = false;
    exportSingleLoading.value = false;
  })
}
// 批量导入用户
const uploadObj = reactive({
  fileType: ['.xls', '.xlsx'],
  accept: '.xls, .xlsx', // 文件上传类型
  multiple: false, // 是否支持多选
  visible: false,
  title: '',
  url: '', // 批量导入用户接口地址
  type:'team',
  downloadObj: {
    name: '',
    url: ''
  }
});
const closeUploadDialog = ()=>{
    uploadObj.visible = false
}
const refreshTable = ()=>{
    ElMessage.success("导入成功！")
    closeUploadDialog()
}

const handleBatchImport = () => {
  let obj1 = {
    title:'批量上架/下架商品',
    url:'商品设置表'
  } 
  uploadObj.visible = true;
  uploadObj.title =  obj1.title;
  uploadObj.url = '/admin/product/excel/imports';
  uploadObj.downloadObj.name = obj1.url; // excel模板名称
  uploadObj.downloadObj.url = `${ossPrefixNew}${obj1.url}.xlsx`; // excel模板下载地址
}
getTableData(true);

</script>

<style lang="scss" scoped>
.layout-container-form {
  position: relative;
  .el-form-item-flexstart{
      display: flex;
      justify-content: flex-start;
      flex-wrap: nowrap;
  }
}

.layout-container-form-search {
  width: 100%;
  display: inline-block !important;
  justify-content: flex-start !important;

  .search-btn {
    margin-right: 10px;
    ;
  }
}

.layout-container-opt {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 10px;
  margin-top: 10px;
}

.split-line {
  margin: 0 8px;
  color: #ccc;
}

.image-slot {
  width: 50px;
  height: 50px;
  background: #fafafa;
  color: #ccc;
  font-size: 12px;
  cursor: pointer;
}
.cup{
    cursor: pointer;
}
.blue{
    color: #027db4;
}
</style>
